#include "checkable_menu.h"

namespace checkable_menu
{

bool is_all_checked(const QList<QAction *> actions)
{
    foreach(QAction * act, actions) {
        if (!act->isChecked())
            return false;
    }
    return true;
}

void set_parent_checked(QMenu *menu, bool check)
{
    if(menu == nullptr)
        return;

    QAction *menuAct = menu->menuAction();
    menuAct->setChecked(check);

    QList<QWidget *> widgets = menuAct->associatedWidgets();
    if (!widgets.isEmpty()) {
        if (QMenu *menu = qobject_cast<QMenu *>(widgets[0])) {
            set_parent_checked(menu, is_all_checked(menu->actions()));
        }
    } else {
        return;
    }
}

void set_children_checked(QMenu *menu, bool check)
{
    if (menu) {
        foreach(QAction * act, menu->actions()) {
            act->setChecked(check);
            set_children_checked(act->menu(), check);
        }
    } else {
        return;
    }
}

menu::menu(QWidget *parent)
    : QMenu(parent)
{
}

menu::menu(const QString &title, QWidget *parent)
    : QMenu(title, parent)
{
}

menu::~menu()
{
    //    qDebug() << "~checkable_menu" << objectName();
}

void menu::set_checked(bool checked)
{
    set_parent_checked  (this, checked);
    set_children_checked(this, checked);
}

void menu::mouseReleaseEvent(QMouseEvent *event)
{
    QAction *action = activeAction();

    if (action && action->isEnabled()) {
        action->setEnabled(false);
        QMenu::mouseReleaseEvent(event); // it's a hack
        action->setEnabled(true);
        action->trigger();

        //        qDebug() << "this" << this << "\n"
        //                 << "activeAction()" << action << "\n"
        //                 << "activeAction()->menu()" << action->menu() << "\n"
        //                 << "activeAction()->parentWidget()" << action->parentWidget() << "\n"
        //                 << "parentWidget()" << parentWidget() << "\n"
        //                 << "associatedWidgets()" << action->associatedWidgets() << "\n"
        //                 << "this->menuAction()" << menuAction() << "\n"
        //                 << "this->menuAction()->associatedWidgets()" << menuAction()->associatedWidgets();

        set_parent_checked(this, is_all_checked(actions()));
        set_children_checked(action->menu(), action->isChecked());
    } else {
        QMenu::mouseReleaseEvent(event);
    }
}

} // end of namespace checkable_menu
